import Vue from 'vue'

/**
 * 处理时间
 * @param time
 * @param cFormat
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return '--'
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+&/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number' && (time.toString().length === 10))) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
    }
    return format.replace(/{(y|m|d|h|i|s)+}/g, (result,key) => {
        let value = formatObj[key]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
}

/**
 * 延迟
 * @param func
 * @param wait
 * @param immediate
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result
    const later = () => {
        //获取时间间隔
        const last = +new Date() - timestamp
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }
    return function (...args) {
        context = this
        //设置当前时间
        timestamp = +new Date()
        //判断是否立即执行
        const callNow = immediate && !timeout
        //如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }
        return result
    }
}


Vue.prototype.parseTime = parseTime;

/**
 * 导出Blob文件
 * @param {Blob} blob 文件流
 * @param {String} name 文件名称
 */
 Vue.prototype.exportFile = (blob, name) => {
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, name);
    } else {
        const blobURL = window.URL.createObjectURL(new Blob([blob]));
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', name);
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }
}

/**
 * 从服务器端下载文件
 * @param {Object} response 响应体信息
 */
 Vue.prototype.downLoadFile = (response) => {
    // content-disposition: attachment;filename=ç¨æ·ä¿¡æ¯.xlsx
    const disposition = response.headers['content-disposition'].split(';');
    const filename = decodeURI(disposition[disposition.length - 1].split("=")[1]);

    const toUnicode = (str) => {
        let txt = escape(str)
            .toLocaleLowerCase()
            .replace(/%u/gi, "\\u");
        txt = txt.replace(/(^\s*)|(\s*$)/g, "");
        return txt
            .replace(/%7b/gi, "{")
            .replace(/%7d/gi, "}")
            .replace(/%3a/gi, ":")
            .replace(/%2c/gi, ",")
            .replace(/%27/gi, "'")
            .replace(/%22/gi, '"')
            .replace(/%5b/gi, "[")
            .replace(/%5d/gi, "]")
            .replace(/%3D/gi, "=")
            .replace(/%20/gi, " ")
            .replace(/%3E/gi, ">")
            .replace(/%3C/gi, "<")
            .replace(/%3F/gi, "?")
            .replace(/%5c/gi, "\\");
    }
    // const name = decodeURI(toUnicode(filename));

    Vue.prototype.exportFile(response.data, filename);
}
